// pages/buy/buy.js
const app = new getApp();
import Dialog from '@vant/weapp/dialog/dialog';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null, //存储用户信息
    stripe: false, //是否为全面屏
    height: "0px", //页面高度
    address: {}, //用户的信息
    building: {}, //所有的地址信息
    popup: false, //修改收货地址的弹窗
    cart:true,//是否是购物车数据
    loading:false,//购买按钮状态
    number:0,//数量
    places: [ //选择宿舍或者教学楼等地点
      {
        text: '宿舍楼',
        value: 1
      },
      {
        text: '教学楼及其它',
        value: 2
      },
    ],
    place: 1, //选择地点后的value值
    dormitorys: [ //选择书院
    ],
    dormitory: 1, //选择书院后的value值
    aPlace: "请选择地点",
    aDormitory: "请选择书院",
    aClassroom: "请选择楼层",
    classrooms: [ //选择教室
    ],
    classroom: 1, //选择楼层后的value值
    aAddress: 0, //区分是教学楼号还是详细地址
    createOrder: {}, //后台返回的信息
    price: 0, //价格
    user: { //存储临时用户信息
      username: "",
      phone: "",
      address: ""
    },
  },
  // 设置地点
  setPlace(e) {
    this.setData({
      aPlace: "",
      place: e.detail,
    })
  },
  //赋值用户名信息
  usernameName: function (e) {
    this.setData({
      user: {
        username: e.detail,
        phone: this.data.user.phone,
        address: this.data.user.address
      },
    })
  },
  //立即购买
  onBuy(){
    this.setData({
      loading:true,
    })
    var user=this.data.userInfo
    var ids=[];
    this.data.createOrder.forEach(e=>{
      ids.push(e.id);
    })
    wx.request({
      url: app.globalData.url + 'updateOrder',
      method: "POST",
      data: {
        id:user.id,
        buildingId:user.buildingId,
        address:user.address,
        openId:user.openId,
        ids:ids,
        phone:user.phone,
        number:this.data.number,
        cart:this.data.cart,
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        if(res.data.state==1){
          wx.redirectTo({
            url: '../buyOk/buyOk?id='+res.data.id,
          })
        }
      }
    })
  },
  //赋值真实姓名信息
  userName(e) {
    this.setData({
      user: {
        username: e.detail,
        phone: this.data.user.phone,
        address: this.data.user.address
      },
      name: e.detail
    })
  },
  //赋值电话信息
  userPhone: function (e) {
    this.setData({
      errPhone: "",
      user: {
        username: this.data.user.username,
        phone: e.detail,
        address: this.data.user.address
      },
    })
  },
  //赋值地址信息
  userAddress: function (e) {
    this.setData({
      user: {
        username: this.data.user.username,
        phone: this.data.user.phone,
        address: e.detail
      },
    })
  },
  //弹出消息层
  customAlert(message,i) {
    Dialog.alert({
      message: message,
    }).then(() => {
      if(i==1){
        this.setData({
          popup: false,
        })
      }
      // on close
    });
  },
  //提交用户信息
  submit() {
    var that = this.data;
    var setData = this;
    var buildingId = 0;
    if (that.user.phone.length != 11) {
      this.customAlert("请输入正确的手机号!");
      return;
    }
    if (that.user.username.length == 0) {
      this.customAlert("请输入真实姓名!");
      return;
    }
    if (that.place == 1) { //选择了宿舍楼
      buildingId = that.dormitory;
    } else if (that.place == 2) { //选择了教学楼
      buildingId = that.classroom;
    } else {
      this.customAlert("请选择地点!");
      return;
    }
    if (buildingId == -1) {
      if (that.place == 1) { //选择了宿舍楼
        this.customAlert("请选择宿舍!");
      } else if (that.place == 2) { //选择了教学楼
        this.customAlert("请选择楼层!");
      }
      return;
    } else {
      if (that.place == 1) { //选择了宿舍楼
        if (that.user.address.length == 0) {
          this.customAlert("请输入正确宿舍号!");
          return;
        }
      } else if (that.place == 2) { //选择了教学楼
        if (that.user.address.length == 0) {
          if (that.aAddress == 1) {
            this.customAlert("请输入正确教学楼号!");
          } else if (that.aAddress == 2) {
            this.customAlert("请输入正确详细地址!");
          }
          return;
        }
      }
      //连接服务器
      var openId = that.userInfo.openId;
      wx.request({
        url: app.globalData.url + 'setUserData',
        method: "POST",
        data: {
          username: that.userInfo.username,
          name: that.user.username, 
          phone: that.user.phone,
          address: that.user.address,
          openId: openId,
          buildingId: buildingId
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success(res) {
          if (res.data.state == 1) {
            setData.customAlert("更新信息完成!",1);
            app.globalData.userInfo = res.data.user;
            
          } else if (res.data.state == 0) {
            wx.showToast({
              title: '更新资料失败！',
              icon: 'error',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '服务器错误！',
              icon: 'error',
              duration: 2000
            })
          }
        },
        fail(res) {
          wx.showToast({
            title: '服务器错误！',
            icon: 'error',
            duration: 2000
          })
        }
      })
    }
  },
  //获取手机号码
  getPhone(e) {
    var that = this;
    var iv = e.detail.iv;
    var encryptedData = e.detail.encryptedData;
    if (iv == encryptedData) {
      Dialog.alert({
        message: '您取消了获取！',
      })
      return;
    }
    wx.login({
      success: res => {
        var code = res.code;
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: app.globalData.url + 'getPhone',
          method: "POST",
          data: {
            code: code,
            encryptedData: encryptedData,
            iv: iv,
          },
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success(res) {
            if (res.data.state == 1) {
              that.setData({
                errPhone: "",
                user: {
                  username: that.data.user.username,
                  phone: res.data.phone,
                  address: that.data.user.address
                },
              })
            }
          }
        })
      }
    });
  },
  //设置宿舍
  setDormitory(e) {
    this.setData({
      aDormitory: "",
      dormitory: e.detail
    })
  },
  //设置楼层
  setClassroom(e) {
    if (e.detail == 0) {
      this.setData({
        aAddress: 2
      });
    } else {
      this.setData({
        aAddress: 1
      });
    }
    this.setData({
      aClassroom: "",
      classroom: e.detail,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          height: res.windowHeight,
          userInfo: app.globalData.userInfo,
        })
      },
    });
    var number = options.number; //数量
    var normId = options.normId; //子商品ID
    var product_id = options.product_id; //母商品ID
    this.createOrder(number, normId, product_id);
    this.getUser();
    this.getBuilding();
  },
  //赋值临时用户信息
  getUser() {
    this.setData({
      user: {
        username: this.data.userInfo.name,
        phone: this.data.userInfo.phone,
        address: this.data.userInfo.address
      }
    })
  },
  //读取商品信息
  createOrder(number, normId, product_id) {
    var that = this;
    var url = app.globalData.url + 'createOrder?user_id=' + this.data.userInfo.id + "&openId=" + that.data.userInfo.openId + "&norm_ids=" + normId;
    if (number != "undefined") {
      url += "&product_num=" + number;
      
      this.setData({
        number:number,
        cart:false,
      })
    }

    wx.request({
      url: url,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        var price = 0;
        res.data.createOrder.forEach(e => {
          price += e.price * e.product_num;
        })
        that.setData({
          price: price,
          createOrder: res.data.createOrder,
        })
      }
    });
  },
  //向服务器读取building
  getBuilding() {
    var that = this;
    wx.request({
      url: app.globalData.url + 'getBuilding',
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        if (res.data.state == 1) {
          that.setData({
            building: res.data.building,
          })
          that.data.building.forEach(e => {
            if (e.id == that.data.userInfo.buildingId) {
              that.setData({
                address: {
                  name: that.data.userInfo.name,
                  phone: that.data.userInfo.phone,
                  address: that.data.userInfo.address,
                  building: e.building,
                  buildingId: that.data.userInfo.buildingId,
                  place: e.place,
                }
              })
              return;
            }
          });
          that.data.building.forEach(function (item) {
            if (item.place == 1) {
              that.data.dormitorys.push({
                text: item.building,
                value: item.id
              });
            } else if (item.place == 2) {
              that.data.classrooms.push({
                text: item.building,
                value: item.id
              });
            }
          });
          that.data.classrooms.push({
            text: '其它',
            value: 0
          });
          that.setData({
            dormitorys: that.data.dormitorys,
            classrooms: that.data.classrooms
          });
        } else {
          that.errorServer(); //服务器发生了错误
        }
      },
      fail(res) {
        that.errorServer(); //服务器发生了错误
      }
    })
  },
  //服务器出现了错误
  errorServer() {
    wx.showToast({
      title: '服务器错误！',
      icon: 'error',
      duration: 2000
    })
  },
  //显示修改收货信息弹框
  revise() {
    if (this.data.address.place == 1) {
      this.setData({
        popup: true,
        aPlace: "",
        aDormitory: "",
        dormitory: parseInt(this.data.address.buildingId),
        place: this.data.address.place,
      })
    } else if (this.data.address.place == 2) {
      if (this.data.address.buildingId == 0) {
        this.setData({
          aAddress: 2
        });
      } else {
        this.setData({
          aAddress: 1
        });
      }
      this.setData({
        popup: true,
        aClassroom: "",
        classroom: parseInt(this.data.address.buildingId),
        place: this.data.address.place,
      })
    }


  },
  //关闭修改收货地址弹框
  onClose() {
    Dialog.confirm({
        title: '即将返回',
        message: '系统不会自动保存您填写信息',
        confirmButtonText: '确认',
      })
      .then(() => {
        this.setData({
          popup: false,
        })
      })
      .catch(() => {});

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    return false;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})